$(function () {
    /*获取保密协议内容*/
    var a = GetRequest();
    var agreement = a['id'];
    $("#confidentialityAgreement").val(agreement);


    /*页面一加载，先隐藏二层数据*/
    $("#medicalReview_direction").attr("style", "display:none;");
    $("#medicines_direction").attr("style", "display:none;");
    $("#record_direction").attr("style", "display:none;");
    $("#scientificResearchSensitive_direction").attr("style", "display:none;");

    /**
     * 点击使用目的（选择医务或者科研）
     */
    $("#purposeState").bind("change", function () {
        var purposeState = $("#purposeState option:selected").val();
        if (purposeState == 1) {
            $("#medicalReview_direction").attr("style", "display:inline;");
            $("#record_direction").attr("style", "display:none;");
            $("#medicines_direction").attr("style", "display:none;");
        } else if (purposeState == 2) {
            $("#record_direction").attr("style", "display:inline;");
            $("#medicalReview_direction").attr("style", "display:none;");
            $("#medicines_direction").attr("style", "display:none;");
        }
    })

    /**
     * 点击权限/敏感（选择权限范围内且无敏感项或者超权限或存在敏感项）
     */
    $("#medicalReview").bind("change", function () {
        var medicalReview = $("#medicalReview option:selected").val();
        if (medicalReview == 1) {
            $("#medicines_direction").attr("style", "display:none;");
        } else if (medicalReview == 2) {
            $("#medicines_direction").attr("style", "display:inline;");
        }
    })

    /**
     * 点击已备案?（选择是或否）
     */
    $("#record").bind("change", function () {
        var record = $("#record option:selected").val();
        if (record == 1) {
            $("#scientificResearchSensitive_direction").attr("style", "display:inline;");
            $("#medicines_direction").attr("style", "display:inline;");
        } else if (record == 2) {
            $("#scientificResearchSensitive_direction").attr("style", "display:none;");
            $("#medicines_direction").attr("style", "display:inline;");
        }
    })


    /*申请信息中的下一项（点击下一项时，表头自动转换）*/
    $("#btn_application_information").click(function () {
        //消除申请信息中的首选
        $("#application_information").removeClass();
        $("#application_information").addClass("col-sm-4 nav1");
        //给查询条件中的class添加active
        $("#query_conditions").addClass("active");
    })
    /*查询条件中的上一项（点击下一项时，表头自动转换）*/
    $("#on_application_information2").click(function () {
        //消除申请信息中的首选
        $("#query_conditions").removeClass();
        $("#query_conditions").addClass("col-sm-4 nav1");
        //给查询条件中的class添加active
        $("#application_information").addClass("active");
    })
    /*查询条件中的下一项（点击上一项时，表头自动转换）*/
    $("#btn_application_information2").click(function () {
        //消除申请信息中的首选
        $("#query_conditions").removeClass();
        $("#query_conditions").addClass("col-sm-4 nav1");
        //给查询条件中的class添加active
        $("#results_the_item").addClass("active");
        //调用查询结果展示的方法
        console.log("调用查询结果展示的方法")
        selectBy();
    })
    /*结果项中的上一项（点击上一项时，表头自动转换）*/
    $("#on_application_information3").click(function () {
        //消除申请信息中的首选
        $("#results_the_item").removeClass();
        $("#results_the_item").addClass("col-sm-4 nav1");
        //给查询条件中的class添加active
        $("#query_conditions").addClass("active");
    })


    /*添加查询信息*/
    $("#btn_personal").click(function () {
        $.ajax({
            url: "../../ClinicalDataQuery/addClinicalDataQuery",
            data: $('#form_personal').serialize(),
            type: "post",
            dataType: "json",
            success: function (map) {
                alert("申请信息添加成功");
            },
            error: function () {
                console.log("数据返回失败");
            }
        });
    })

    /**
     * 点击左侧确定按钮保存数据，在右侧自动添加
     */
    $("#btn").click(function () {
        var ids = [];
        $("input[name='xz']:checked").each(function (i) {
            ids.push($(this).val())
        })
        if (ids.length != 0) {
            display(ids);
        }
    })

    /**
     * 点击保存按钮，保存提取的查询条件
     */
    $("#btn_personal2").click(function () {
        var ids = [];
        $("input[name='xz']:checked").each(function (i) {
            ids.push($(this).val())
        })
        if (ids.length != 0) {
            insertPlay(ids);
        }
    })

    /**
     * 点击结果项，查询条件保存提取的查询条件，并展示会页面查询数量
     */
    $("#results_the_item").click(function () {
        selectBy();
    })

    /**
     * 点击结果项中的保存按钮，实现新增按钮数据的最后保存，存入数据库中
     */
    $("#btn_personal3").click(function () {
        console.log("点击结果项中的保存");
        $.ajax({
            url: "../../ClinicalDataQuery/addBy",
            type: "post",
            dataType: "json",
            success: function (map) {
                alert("结果保存成功");
                top.location.href = "/page/ClinicalDataQuerySystem/clinicalDataQueryDisplay.jsp"
            }
        })
    })

    /**
     * 向页面展示信息，拼接信息字段
     * @param ids
     */
    function display(ids) {
        var htmlstr = "";
        /*向页面上拼接数据*/
        var len = ids.length;
        var ANDPX = (len % 2) == 0 ? (len / 2) * 50 : ((len / 2) + 0.5) * 50;
        htmlstr += "<div class='wap'>";
        htmlstr += "<div id='left' style='height: " + ANDPX + "px; line-height: " + ANDPX + "px;'>AND";
        htmlstr += "</div>";
        htmlstr += "<div id='left1'>";
        for (var i = 0; i < len / 2; i++) {
            htmlstr += "<div class='left1' style='height: 40px; line-height: 40px;'>OR";
            htmlstr += "</div>";
        }
        htmlstr += "</div>";
        htmlstr += "<div id='left2'>";
        for (var i = 0; i < len; i++) {
            var index = ids[i].split(",");
            var columenName = "";   //字段名称
            var columenComment = "";    //注释名称
            for (var j = 0; j < index.length; j++) {
                if (j == 0) {
                    columenName = index[j];
                } else {
                    columenComment = index[j];
                }
            }
            /*拼接属性*/
            htmlstr += "<div class='left2 btn-toolbar' role='toolbar'>";
            htmlstr += "<div class='btn-group btn-group-xs'>";
            htmlstr += "<button type='button' class='btn btn-default' style='width: 110px;'>";
            htmlstr += "" + columenComment + "";
            htmlstr += "</button>";
            if (columenName.indexOf("date") != -1 || columenName.indexOf("days") != -1 || columenName.indexOf("time") != -1) {
                htmlstr += "<select id='query" + i + "' class='btn btn-default' style='margin-left: 5px;'>"
                htmlstr += "<option value='>'>大于</option>";
                htmlstr += "<option value='='>等于</option>";
                htmlstr += "<option value='<'>小于</option>";
                htmlstr += "<option value='&gt;='>开始于</option>";
                htmlstr += "<option value='&lt;='>结束于</option>";
                htmlstr += "</select>";
            } else {
                htmlstr += "<select id='query" + i + "' class='btn btn-default' style='margin-left: 5px;'>"
                htmlstr += "<option value='=' selected>等于</option>";
                htmlstr += "</select>";
            }
            console.log(columenName.indexOf("date") != -1)
            if (columenName.indexOf("date") != -1 || columenName.indexOf("time") != -1) {
                htmlstr += "<input id='queryConditions" + i + "' type='date' style='width: 300px; margin-left: 5px;' class='btn btn-default'/>";
            } else if (columenName.indexOf("days") != -1) {
                htmlstr += "<input id='queryConditions" + i + "' style='width: 300px; margin-left: 5px;'class='btn btn-default' />";
            } else {
                htmlstr += "<input id='queryConditions" + i + "' style='width: 300px; margin-left: 5px;' class='btn btn-default'/>";
            }
            htmlstr += "</div>";
            htmlstr += "</div>";
        }
        htmlstr += "</div>";
        htmlstr += "<div id='left3'>";
        /*for (var i = 0; i < len ; i++) {
            htmlstr += "<div class='left3'>";
                htmlstr += "<i class='glyphicon glyphicon-trash' id=''></i>";
            htmlstr += "</div>";
        }*/
        htmlstr += "</div>";
        htmlstr += "</div>";
        $(".wapReight").html(htmlstr);
    }

    /**
     * 选择的查询条件存放到数据库中
     * @param ids
     */
    function insertPlay(ids) {
        var query_field = []; //查询字段
        var query = [];    //查询方式
        var query_conditions = []; //查询条件
        var scope_of = []; //查询结果展示范围
        var scope_of_id = $("input[name='scope_of']:checked").val();
        for (var i = 0; i < ids.length; i++) {
            var index = ids[i].split(",");
            var columenName = "";   //字段名称
            var columenComment = "";    //注释名称
            for (var j = 0; j < index.length; j++) {
                if (j == 0) {
                    columenName = index[j];
                } else {
                    columenComment = index[j];
                }
            }
            /*插入数据库中拼接*/
            query_field.push(columenName + "-" + columenComment);
            query.push($("#query" + i + " :selected").val());
            query_conditions.push($("#queryConditions" + i + "").val());
            scope_of.push(scope_of_id);
        }
        /*保存到数据库中的Ajax*/
        $.ajax({
            url: "../../ClinicalDataQuery/addQueryConditions",
            type: "post",
            data: 'query_field=' + query_field + '&query=' + query + '&query_conditions=' + query_conditions + '&scope_of=' + scope_of,
            dataType: "json",
            success: function (map) {
                alert("查询条件添加成功");
            }
        })
    }

    /**
     * 展示查询结果后的数据
     */
    function selectBy() {
        $.ajax({
            url: "../../ClinicalDataQuery/selectBy",
            type: "post",
            dataType: "json",
            success: function (map) {
                var count = map.count;
                $("#spanCount1").text(count);
                var query_field = map.query_field;
                var query = map.query;
                var query_conditions = map.query_conditions;
                var scope_of = map.scope_of;
                var htmlStr = "";
                if (query_field != null) {
                    for (var i = 0; i < query_field.length; i++) {
                        var query_field_name = query_field[i].substring(query_field[i].indexOf("-") + 1, query_field[i].length);
                        htmlStr += "<tr>";
                        htmlStr += "<td align='right'>" + query_field_name + "</td>";
                        htmlStr += "<td align='center'>" + query[i] + "</td>";
                        htmlStr += "<td>" + query_conditions[i] + "</td>";
                        htmlStr += "</tr>";
                    }
                }
                $("tbody").html(htmlStr);
            }
        })
    }

    /**
     * 通过路径获取id
     * @returns
     */
    function GetRequest() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }


})